package com.lzp.java.concurrent.threadcore.stopthread;

/**
 * catch子语句中调用Thread.currentThread().interrupt()来恢复设置中断状态，
 * 以便于在后续的执行中，依然能够检查到刚才发生了中断
 *
 * @author lzp
 * @date 2020/01/31
 */
public class RightWayStopThreadInProduct2 implements Runnable {
    @Override
    public void run() {
        while (true) {
            // 检测子方法中断的中断位，退出循环
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("线程中断，程序运行结束");
                break;
            }
            subTask();
        }
    }

    private void subTask() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // 恢复中断
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProduct2());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}
